#!/bin/bash

set -e
set -x

# https://downloads.apache.org/kafka/3.9.0/kafka_2.13-3.9.0.tgz
bypy download kafka_2.13-3.9.0.tgz
tar xf kafka_2.13-3.9.0.tgz
sh render.sh

iplist_path=config
i=0
while read -r line
do
    case $line in
        *'#'*)
            continue
        ;;
        *'end'*)
            break
        ;;
        *)
            IFS=',' read -ra parts <<< "$line"
        ;;
    esac
    
    pass="${parts[0]}" 
    address="${parts[1]}"
    hostname="${parts[2]}"
    if [ $address ];then
        sshpass -p$pass scp kafka_2.13-3.9.0.tgz $address:/opt/
        sshpass -p$pass ssh -n $address tar xf /opt/kafka_2.13-3.9.0.tgz -C /opt/
        sshpass -p$pass ssh -n $address mv /opt/kafka_2.13-3.9.0 /opt/kafka
        sshpass -p$pass ssh -n $address 'echo "JAVA=$JAVA_HOME" >> /opt/kafka/env'
        sshpass -p$pass ssh -n $address 'echo "PATH=$PATH" >> /opt/kafka/env'
        cp server.properties.tpl server.properties
        sed -i "s/(node-id)/$i/" server.properties
        sed -i "s/(localhost)/$hostname/g" server.properties
        sshpass -p$pass scp server.properties $address:/opt/kafka/config/kraft/server.properties
        sshpass -p$pass scp format.sh $address:/opt/kafka/
        sleep 1
        sshpass -p$pass ssh -n $address sh /opt/kafka/format.sh
        sshpass -p$pass scp kafka.service $address:/usr/lib/systemd/system/
        sshpass -p$pass ssh -n $address systemctl daemon-reload
        sshpass -p$pass ssh -n $address systemctl enable --now kafka
        let i=i+1
    fi
done < $iplist_path

# /opt/kafka/bin/kafka-topics.sh --create --topic tophant.test --bootstrap-server localhost:9092 --if-not-exists

set +x
set +e